package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page,Integer pageSize,String name){
        Page<DishDto> dishDtoPage = dishService.selectPageByName(page, pageSize, name);
        return R.success(dishDtoPage);
    }
    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto){
        dishService.saveWithFlavors(dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("菜品保存成功");
    }
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.selectByIdWithFlavors(id);
        return R.success(dishDto);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavors(dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("更新成功");
    }

    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish){
        String key = "dish_"+dish.getCategoryId();
        List<DishDto> dishDtos = redisTemplate.opsForList().range(key, 0, -1);
        if (dishDtos == null || dishDtos.size() == 0){
            dishDtos = dishService.listWithFlavors(dish);
            redisTemplate.opsForList().rightPushAll(key,dishDtos);
        }
        return R.success(dishDtos);
    }

}
